package com.laob.laob_special.util;

import com.alibaba.fastjson.JSONObject;
import com.laob.laob_special.common.PoolTest;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author zhangh     
 * @version V1.0.0
 * @projectName laob_special
 * @title     HttpClientUtils   
 * @package    com.laob.laob_special.util  
 * @date   2019/9/9 14:07  
 * @explain
 */
@Component
@SuppressWarnings("all")
public class HttpClientPoolUtils {

    // 用来存储可用端口
    public static volatile List<Integer> realPorts;
    // 用来终止线程
    public static volatile Boolean flag = true;
    ;

    private static void config(HttpRequestBase httpRequestBase) {
        httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
        httpRequestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
        httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");

        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(1500)
                .setConnectTimeout(1500)
                .setSocketTimeout(1500)
                .build();
        httpRequestBase.setConfig(requestConfig);
    }

    // Get请求多线程
    static class GetRunnable implements Runnable {
        private CountDownLatch countDownLatch;
        private final CloseableHttpClient httpClient;
        private final HttpGet httpget;
        private final Integer port;

        public GetRunnable(CloseableHttpClient httpClient, HttpGet httpget, CountDownLatch countDownLatch, Integer port) {
            this.httpClient = httpClient;
            this.httpget = httpget;
            this.countDownLatch = countDownLatch;
            this.port = port;
        }

        @Override
        public void run() {
            CloseableHttpResponse response = null;
            JSONObject jsonResult = null;
            String strResult = null;
            try {
                System.out.println("get==============" + port);
                response = httpClient.execute(httpget, HttpClientContext.create());
                //if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                // 不用管状态码,如果服务器响应数据,哪怕错误,也说明该端口可访问
                HttpEntity entity = response.getEntity();
                strResult = EntityUtils.toString(entity, "utf-8");
                if (!StringUtils.isEmpty(strResult) && strResult.length() > 0) {
                    realPorts.add(port);
                }
                //} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                //    // 发生重定向说明端口也可用
                //    realPorts.add(port);
                //}
            } catch (IOException e) {
                //e.printStackTrace();
            } finally {
                countDownLatch.countDown();
                System.out.println("get==============end" + port);
                try {
                    if (response != null)
                        response.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }
    }

    // Post请求多线程
    static class PostRunaable implements Runnable {
        private CountDownLatch countDownLatch;
        private final CloseableHttpClient httpClient;
        private final HttpPost httpPost;
        private final Integer port;

        public PostRunaable(CloseableHttpClient httpClient, HttpPost httpPost, CountDownLatch countDownLatch, Integer port) {
            this.httpClient = httpClient;
            this.httpPost = httpPost;
            this.countDownLatch = countDownLatch;
            this.port = port;
        }

        @Override
        public void run() {
            CloseableHttpResponse response = null;
            JSONObject jsonResult = null;
            String strResult = null;
            try {
                System.out.println("post==============" + port);
                response = httpClient.execute(httpPost, HttpClientContext.create());
                System.out.println(httpPost);
                //if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                strResult = EntityUtils.toString(entity, "utf-8");
                if (!StringUtils.isEmpty(strResult) && strResult.length() > 0) {
                    realPorts.add(port);
                }
                //} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
                //    // 重定向,说明端口也可用
                //    realPorts.add(port);
                //}

            } catch (IOException e) {
                //e.printStackTrace();
            } finally {

                countDownLatch.countDown();
                System.out.println("post==============end" + port);
                try {
                    if (response != null)
                        response.close();
                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }
    }

    //
    public static List<Integer> testPort(String ipAddress, String type, Integer minPort, Integer maxPort, String method) {

        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加到200
        cm.setMaxTotal(maxPort - minPort); // maxPort - minPort
        // 将每个路由基础的连接增加到20
        cm.setDefaultMaxPerRoute(200);

        // 将目标主机的最大连接数增加到50
        HttpHost localhost = new HttpHost(ipAddress, 80);
        cm.setMaxPerRoute(new HttpRoute(localhost), 50);

        //请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 5) {// 如果已经重试了5次，就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接，那么就重试
                    return false;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// ssl握手异常
                    return false;
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的，就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRetryHandler(httpRequestRetryHandler)
                .build();


        long start = System.currentTimeMillis();
        try {
            ExecutorService executors = Executors.newFixedThreadPool(maxPort - minPort);
            //Future future = null;
            CountDownLatch countDownLatch = new CountDownLatch(maxPort - minPort);
            System.out.println("thread-pool num -->" + (maxPort - minPort));
            if ("get".equalsIgnoreCase(type)) {
                for (int i = minPort + 1; i <= maxPort; i++) {
                    if (!flag) {
                        break;
                    }
                    HttpGet httpget = new HttpGet(ipAddress + ":" + i + method);
                    config(httpget);
                    //启动线程抓取
                    executors.execute(new GetRunnable(httpClient, httpget, countDownLatch, i));
                }
                //future.get();
            } else if ("post".equalsIgnoreCase(type)) {
                for (int i = minPort + 1; i <= maxPort; i++) {
                    if (!flag) {
                        break;
                    }
                    HttpPost httpPost = new HttpPost(ipAddress + ":" + i + method);
                    config(httpPost);

                    //启动线程抓取
                    executors.execute(new PostRunaable(httpClient, httpPost, countDownLatch, i));
                }
                //future.get();
            }
            // 如果没有收到终止信息,就等待线程执行完成
            if (flag) {
                countDownLatch.await();
            }
            executors.shutdown();
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (!flag){
                System.out.println("==================执行终止扫描====================");
            }
            System.out.println("线程" + Thread.currentThread().getName() + "," + System.currentTimeMillis() + ", 所有线程已完成，开始进入下一步！");
        }

        long end = System.currentTimeMillis();
        System.out.println("consume -> " + (end - start));
        return realPorts;
    }

}
